﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data;

namespace Ex6.UsingSMO
{
    class BackUpAndRestoreToNewDB
    {
        public static void Main()
        {
            Server myServer = new Server(@".\SQLEXPRESS");
            try
            {
                myServer.ConnectionContext.LoginSecure = true;
                myServer.ConnectionContext.Connect();

                //BackupDatabaseFull(myServer, myServer.Databases["Northwind"]);
                //GetLogicalNamesOfBackUp(myServer);
                //RestoreDatabaseWithDifferentNameAndLocation(myServer, myServer.Databases["Northwind"]);

                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.InnerException.Message);
            }
            finally
            {
                if (myServer.ConnectionContext.IsOpen)
                    myServer.ConnectionContext.Disconnect();
            }
        }

        private static void GetLogicalNamesOfBackUp(Server myServer)
        {
            Restore res = new Restore();
            DataTable dt;
            DataRow[] foundrows;

            res.Devices.AddDevice(@"D:\NorthwindFull.bak", DeviceType.File);
            dt = res.ReadFileList(myServer);

            foundrows = dt.Select();

            foreach (DataRow r in foundrows)
            {
                Console.WriteLine(r["LogicalName"].ToString());
            }
        }

        private static void BackupDatabaseFull(Server myServer, Database myDatabase)
        {
            Backup bkpDBFull = new Backup();

            bkpDBFull.Action = BackupActionType.Database;

            bkpDBFull.Database = myDatabase.Name;

            bkpDBFull.Devices.AddDevice(@"D:\NorthwindFull.bak", DeviceType.File);
            bkpDBFull.BackupSetName = "Northwind database Backup";
            bkpDBFull.BackupSetDescription = "Northwind database - Full Backup";

            bkpDBFull.ExpirationDate = DateTime.Today.AddDays(10);
            bkpDBFull.Initialize = false;

            bkpDBFull.PercentComplete += CompletionStatusInPercent;
            bkpDBFull.Complete += Backup_Completed;

            bkpDBFull.SqlBackup(myServer);
        }

        private static void RestoreDatabaseWithDifferentNameAndLocation(Server myServer, Database myDatabase)
        {
            Restore restoreDB = new Restore();
            restoreDB.Database = myDatabase.Name + "Twin";
            restoreDB.Action = RestoreActionType.Database;
            restoreDB.Devices.AddDevice(@"D:\NorthwindFull.bak", DeviceType.File);

            restoreDB.ReplaceDatabase = true;
            restoreDB.NoRecovery = true;

            restoreDB.RelocateFiles.Add(new RelocateFile("Northwind", @"D:\NorthwindTwin.mdf"));
            restoreDB.RelocateFiles.Add(new RelocateFile("Northwind_log", @"D:\NorthwindTwin_log.ldf"));


            restoreDB.PercentComplete += CompletionStatusInPercent;
            restoreDB.Complete += Restore_Completed;

            restoreDB.SqlRestore(myServer);
        }

        private static void CompletionStatusInPercent(object sender, PercentCompleteEventArgs args)
        {
            Console.Clear();
            Console.WriteLine("Percent completed: {0}%.", args.Percent);
        }

        private static void Backup_Completed(object sender, ServerMessageEventArgs args)
        {
            Console.WriteLine("Hurray...Backup completed.");
            Console.WriteLine(args.Error.Message);
        }

        private static void Restore_Completed(object sender, ServerMessageEventArgs args)
        {
            Console.WriteLine("Hurray...Restore completed.");
            Console.WriteLine(args.Error.Message);
        }
    }
}
